# coding=utf-8
import json

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many, db_exec_one
from model.c_department import find_all_depart


def sync_depart():
    # 1 查询数据库中所有专有云
    # p_cloud_list = find_cloud_by_type('private')  # 只有专有云需要根据root ak/sk ，定期扫描找到所有组织信息
    params = {"Id": 1}
    asapi_data = request_asapi("1", "ascm", "2019-05-10", "GetOrganizationList", params)  # todo:写死了无锡专有云
    if not asapi_data:
        return False
    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for i in asapi_data['data']:
        if i['parentId'] != 1:  # 只记录一级部门
            continue
        tmp_tuple = (i['id'], i['name'], i['status'], '1')
        values_list.append(tmp_tuple)
    table = 'c_department'
    fields = "department,department_name,status,cloud_id"
    values = "%s,%s,%s,%s"
    sql = "INSERT IGNORE INTO {}({}) VALUES({});".format(table, fields, values)

    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list, sql=sql)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/sync_depart', methods=['POST'])
def sync_depart_api():
    success = sync_depart()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})


# 调用GetPrivateCloudAccountByOrganizationId获取一级组织对应的主账号信息。
def sync_depart_account(depart_id) -> bool:
    # 创建一个asapi的客户端
    asapi_data = request_asapi(1, "ascm", "2019-05-10", "GetPrivateCloudAccountByOrganizationId",
                               {"OrganizationId": depart_id})
    if not asapi_data:
        return False
    # 准备插入数据库
    sql = "UPDATE c_department SET aliyunid='{}' WHERE department='{}';".format(asapi_data['data']['aliyunid'],
                                                                                depart_id)
    # 插入db
    db_success = db_exec_one(sql)
    if not db_success:
        return False
    return True


def sync_depart_accounts() -> bool:
    departs = find_all_depart()
    for depart in departs:
        success = sync_depart_account(depart['department'])
        if not success:
            return False
    return True


@bp.route('/api/v1/cloud/sync_depart_account', methods=['POST'])
def sync_depart_account_api():
    success = sync_depart_accounts
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
